package com.hyh.shipment.mqlistener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyh.feign.clients.OrderClient;
import com.hyh.feign.clients.ProductClient;
import com.hyh.feign.domain.Orders;
import com.hyh.feign.domain.Product;
import com.hyh.shipment.constants.PayConstants;
import com.hyh.shipment.dao.ShipmenMapper;
import com.hyh.shipment.domain.Shipment;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

@Component
public class MqListener {

    @Autowired
    private OrderClient orderClient;

    @Autowired
    private ShipmenMapper shipmenMapper;

    @Autowired
    private ProductClient productClient;

    // 监听mq发来的消息
    @RabbitListener(queues = PayConstants.PAY_QUEUE)
    public void updateListener(Long orderNumber){
        Orders orderById = orderClient.getOrderById(orderNumber);
        // 更新库存
        productClient.updateStock(Long.valueOf(orderById.getProductId()),orderById.getPurchaseCount());
        Product productById = productClient.getProductById(Long.valueOf(orderById.getProductId()));
        Shipment shipment = new Shipment();
        shipment.setShipmentDate(new Timestamp(System.currentTimeMillis() + 1000 * 60 * 60 * 8 ));
        shipment.setOrderId(Math.toIntExact(orderById.getId()));
        shipment.setQuantity(orderById.getPurchaseCount());
        shipment.setTotal(productById.getStockQuantity());
        shipment.setAddress(Long.valueOf(orderById.getUserId()));
        shipment.setProductId(orderById.getProductId());
        shipment.setOrderNumber(orderNumber);
        shipmenMapper.insert(shipment);
    }
}
